<template>
  <div class="school-course">
    <el-dialog
      title="新增报课"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="1000px"
      height="700px"
    >
      <el-form :model="form" ref="form" label-width="100px" :rules="formRules">
        <h4>基本信息</h4>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标题：" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入标题"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包含年级：" prop="grade">
              <nice-select
                v-model="form.grade"
                placeholder="请选择包含年级"
                clearable
                :options="gradeList"
                :multiple="true"
                @change="handleChange"
              ></nice-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选课模式：" prop="chooseCourseType">
              <nice-select
                v-model="form.chooseCourseType"
                placeholder="请选择选课模式"
                clearable
                :options="courseModeList"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="辅导模式：" prop="choose_tutor">
              <nice-select
                v-model="form.choose_tutor"
                placeholder="请选择辅导模式"
                clearable
                :options="tutorModeList"
              ></nice-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮寄地址：" prop="is_open_address">
              <nice-select
                v-model="form.is_open_address"
                placeholder="请选择邮寄地址"
                clearable
                :options="emailList"
              ></nice-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择优惠：" prop="preferentialType">
              <nice-select
                v-model="form.preferentialType"
                placeholder="请选择优惠"
                clearable
                :options="favoureList"
              ></nice-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div
          v-for="(item, index) in form.gradeGoods"
          :key="index"
          class="margin-bottom20"
        >
          <h4>
            {{ item.grade }}
            <i
              class="el-icon-delete margin-left10"
              @click="deleteGrade(item, index)"
            ></i>
          </h4>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="拟接入数："
                :prop="'gradeGoods.' + index + '.num'"
                :rules="[
                  { required: true, message: '请输入拟接入数', trigger: 'blur' }
                ]"
              >
                <el-input
                  v-model="item.num"
                  placeholder="请输入拟接入数"
                  clearable
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="辅导："
                :prop="'gradeGoods.' + index + '.teacher'"
              >
                <el-select
                  v-model="item.teacher"
                  placeholder="请输入选择辅导"
                  clearable
                  multiple
                  :disabled="form.choose_tutor == 0"
                  @visible-change="test(item)"
                  @change="changeTutor"
                >
                  <el-option
                    v-for="item in teacherList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <div
            v-for="(ele, $index) in item.list"
            :key="$index"
            class="margin-bottom20"
            @click="test(item)"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  label="商品："
                  :prop="
                    'gradeGoods.' + index + '.list.' + $index + '.goodname'
                  "
                >
                  <el-select
                    v-model="ele.goodname"
                    filterable
                    remote
                    reserve-keyword
                    placeholder="请输入商品名称"
                    :disabled="$index != item.list.length - 1"
                    :remote-method="remoteGoodsMethod"
                    :loading="goodloading"
                    clearable
                    @change="changeGood($event, index, $index)"
                  >
                    <el-option
                      v-for="good in goodList"
                      :key="good.value"
                      :label="good.label"
                      :value="good.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="2"
                class="margin-top10 margin-left10"
                v-if="$index != item.list.length - 1"
              >
                <i
                  class="el-icon-delete"
                  @click="deleteGood(index, $index)"
                ></i>
              </el-col>
            </el-row>
            <div v-for="(course, indx) in ele.courseList" :key="indx">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="课程名称：">
                    <span>{{ course.label }}</span>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="选择期次："
                    :prop="
                      'gradeGoods.' +
                        index +
                        '.list.' +
                        $index +
                        '.courseList.' +
                        indx +
                        '.period'
                    "
                  >
                    <nice-select
                      v-model="course.period"
                      placeholder="请选择期次"
                      clearable
                      :options="course.periodList"
                      :disabled="$index != item.list.length - 1"
                    ></nice-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <el-button
              type="primary"
              @click="save(ele, index)"
              size="small"
              v-if="$index == item.list.length - 1"
              >保存</el-button
            >
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  queryCounselorList,
  queryGoodsListByTerm,
  insertCoursePlanAndDetail,
  editCoursePlanAndDetail,
  queryCoursePlanDetails
} from "@/api/user.js";
import {
  enrollmentPlan,
  editEnrollmentPlan,
  queryTutorList,
  queryEnrollmentDetail
} from "@/api/api.js";
import _ from "underscore";
export default {
  data() {
    return {
      visible: false,
      id: "",
      teacherList: [],
      termList: [],
      form: {
        title: "",
        grade: [],
        chooseCourseType: 0,
        choose_tutor: 1,
        is_open_address: 0,
        preferentialType: "",
        gradeGoods: []
      },
      goodList: [],
      goodloading: false,
      courseModeList: [
        { label: "不允许学生自主选课", value: 0 },
        { label: "允许学生自主选课", value: 1 }
      ],
      tutorModeList: [
        { label: "不指定辅导", value: 0 },
        { label: "指定辅导", value: 1 }
      ],
      emailList: [
        { label: "关闭邮寄地址填写", value: 0 },
        { label: "开启邮寄地址填写", value: 1 }
      ],
      formRules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        grade: [
          { required: true, message: "请选择学生年级", trigger: "change" }
        ],
        chooseCourseType: [
          { required: true, message: "请选择选课模式", trigger: "change" }
        ],
        is_open_address: [
          { required: true, message: "请选择邮寄地址", trigger: "change" }
        ],
        preferentialType: [
          { required: true, message: "请选择优惠", trigger: "change" }
        ]
      }
    };
  },
  props: {
    gradeList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    selectEnums: {
      type: Array,
      default: function() {
        return [];
      }
    },
    favoureList: {
      type: Array,
      default: function() {
        return [];
      }
    },
    schoolId: ""
  },
  created() {
    // this.getTeacherList();
  },
  methods: {
    init() {
      this.visible = true;
      this.$nextTick(() => {
        this.goodList = [];
        this.termList = [];
        this.$refs.form.resetFields();
        this.form.favorable = this.favoureList[1].value;
        this.form.gradeGoods = [];
        this.getTeacherList();
      });
    },
    test(item) {
      let id = arguments[0].id;
      this.getTeacherList(id);
    },
    return_grade_name(val) {
      let res = _.filter(this.gradeList, function(item) {
        return item.value == val;
      });
      return res[0].label;
    },
    getdetailsinfo(course_plan_id) {
      this.getTeacherList();
      this.id = course_plan_id;
      this.visible = true;
      var _this = this;
      queryEnrollmentDetail({ course_plan_id }).then(res => {
        let _res = res[1].data.enrollment_plan[0];
        this.form = Object.assign({}, _res);
        this.form.grade = _res.grades.split(",");
        this.form.grade = this.form.grade.map(Number);
        this.form.gradeGoods = [];
        this.form.chooseCourseType = _res.choose_course_type;
        this.form.preferentialType = _res.preferential_type;
        _res.gradeList.forEach((item, index) => {
          let grade_name = _this.return_grade_name(item.grade);
          let _list = item.courseList;
          let list_res = [];
          _list.forEach((s, v) => {
            list_res.push({
              goodname: s.goods_id,
              goods_id: s.goods_id,
              courseList: [
                {
                  value: s.course_id,
                  label: s.goods_name,
                  period: s.course_period_id,
                  goods_id: s.goods_id,
                  periodList: [
                    {
                      label: "",
                      coursePeriodId: s.course_period_id,
                      value: s.course_period_id,
                      periodSort: s.period_sort,
                      sort: s.period_sort
                    }
                  ]
                }
              ]
            });
          });
          let _tutorList = _.pluck(item.tutorList, "tutor_id");
          let _objs = {
            grade: grade_name,
            id: item.grade,
            num: item.courseList[0].plan_num,
            teacher: _tutorList.map(String),
            list: list_res
          };
          this.form.gradeGoods.push(_objs);
        });
        console.log("this.form.grade", this.form.grade);
        console.log("res", _res.gradeList);
      });
    },
    deleteGood(index, indx) {
      this.form.gradeGoods[index].list[indx].splice(indx, 1);
    },
    changeTutor(e) {
      console.log("e===>", e);
    },
    handleChange() {
      this.form = Object.assign({}, this.form, {
        gradeGoods: []
      });
      if (this.gradeList && this.gradeList.length) {
        this.gradeList.forEach(ele => {
          this.form.grade.forEach(item => {
            if (item == ele.value) {
              this.form.gradeGoods.push({
                grade: ele.label,
                id: ele.value,
                num: "",
                teacher: "",
                list: [
                  {
                    goodname: "",
                    courseList: []
                  }
                ]
              });
            }
          });
        });
      }
      console.log("this.form.gradeGoods", this.form.gradeGoods);
    },
    async getTeacherList(grade = "") {
      let res = await queryTutorList({
        currPage: 1,
        pageSize: 100,
        grade: grade
      });
      if (res[0]) {
        return;
      }
      if (res[1] && res[1].code === 0) {
        this.teacherList = [];
        console.log("res[1]", res[1]);
        if (res[1].data.list && res[1].data.list.length) {
          res[1].data.list.forEach(ele => {
            this.teacherList.push({
              label: ele.realName,
              value: ele.id,
              studentUpper: ele.studentUpper
            });
          });
        }
      }
      console.log("this.teacherList", this.teacherList);
    },
    async remoteGoodsMethod(query) {
      if (query !== "") {
        this.goodloading = true;
        let res = await queryGoodsListByTerm({ goods_name: query });
        if (res[0]) {
          return;
        }
        this.goodloading = false;
        if (res[1] && res[1].code === 0) {
          this.goodList = [];
          if (res[1].coursePlanList && res[1].coursePlanList.length) {
            this.goodList = res[1].coursePlanList.map(ele => {
              return {
                label: ele.goods_name,
                value: ele.id,
                courseList: ele.courseList
              };
            });
          }
        }
      }
    },
    save(item, index) {
      if (!item.goodname) {
        this.$message.warning("请选择商品！");
        return;
      }

      if (item.courseList && item.courseList.length) {
        let result = [];
        item.courseList.forEach(ele => {
          if (!ele.period) {
            result.push(ele);
          }
        });
        if (result && result.length) {
          this.$message.warning("请选择期次！");
          return;
        }
      }
      this.form.gradeGoods[index].list.push({
        goodname: "",
        courseList: []
      });
    },
    deleteGrade(item, index) {
      this.form.grade.forEach((ele, indx) => {
        if (ele == item.id) {
          this.form.grade.splice(indx, 1);
        }
      });
      this.form.gradeGoods.splice(index, 1);
    },
    dataFormSubmit() {
      let gradeList = [];
      this.form.gradeGoods.forEach((item, index) => {
        let _s = [];
        let tutorList = [];
        item.teacher.map(teacher => {
          tutorList.push({ tutorId: teacher });
        });
        item.list.forEach((_item, _index) => {
          let _ag = {};
          if (_item.goodname) {
            _ag.goodsId = _item.goodname;
            _ag.courseId = _item.courseList[0].value;
            _ag.coursePeriodId = _item.courseList[0].period;
            _ag.periodSort = _item.courseList[0].periodList[0].periodSort;
            _ag.planNum = item.num;
            _ag.grade = item.id;
            _s.push(_ag);
          }
        });
        let _obj = {
          grade: item.id, // 年级
          planNum: item.num,
          tutorList: tutorList,
          courseList: _s
        };
        gradeList.push(_obj);
      });
      let params = {
        title: this.form.title,
        choose_tutor: this.form.choose_tutor,
        schoolId: this.$route.params.id,
        grades: this.form.grade.join(","),
        preferentialType: this.form.preferentialType,
        chooseCourseType: this.form.chooseCourseType,
        is_open_address: this.form.is_open_address,
        choose_tutor: this.form.choose_tutor,
        gradeList,
        id: this.id
      };
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let res = this.id
            ? await editEnrollmentPlan(params)
            : await enrollmentPlan(params);
          if (res[0]) {
          }
          if (res[1] && res[1].code === 0) {
            this.$message.success(
              this.id ? "编辑学校报课成功！" : "新增学校报课成功！"
            );
            this.visible = false;
            this.$emit("refreshDataList");
          }
        }
      });
    },
    changeGood(val, index, indx) {
      console.log(val, index, indx);
      this.goodList.forEach(ele => {
        if (val === ele.value) {
          this.courseList = [];
          if (ele.courseList && ele.courseList.length) {
            ele.courseList.forEach(item => {
              let periodList = [];
              if (item.coursePeriodList && item.coursePeriodList.length) {
                item.coursePeriodList.forEach(period => {
                  period.start_date = period.start_date
                    ? period.start_date.substring(0, 10)
                    : "";
                  period.end_date = period.end_date
                    ? period.end_date.substring(0, 10)
                    : "";
                  let date = period.start_date
                    ? period.start_date + "~" + period.end_date
                    : "";
                  let frequency = period.frequency
                    ? JSON.parse(period.frequency)
                    : [];
                  let week = "周" + this.$filterFrequency(frequency);
                  period.label =
                    "第" + period.sort + "期" + " " + date + " " + week;
                  periodList.push({
                    label: period.label,
                    coursePeriodId: period.id,
                    value: period.id,
                    periodSort: period.sort,
                    sort: period.sort
                  });
                });
              }
              this.courseList.push({
                value: item.course_id,
                label: item.course_name + " " + item.total_lesson + "讲",
                period: "",
                goods_id: item.goods_id,
                periodList: periodList
              });
            });
            this.$set(this.form.gradeGoods[index].list, indx, {
              goodname: val,
              goods_id: val,
              courseList: this.courseList
            });
          }
        }
      });
      this.goodList = [];
    }
  }
};
</script>
<style lang="scss" scoped>
.school-course {
  h4 {
    border-bottom: 1px solid #e5e5e5;
    padding-bottom: 10px;
  }
}
.good-item {
  margin-bottom: 20px;
  .line {
    height: 1px;
    background: #dcdfe6;
    margin-left: 10px;
  }
}
</style>
